/**
 * @author {Yuntao Zhou}
 */
 if(!String.format){
	String.format = function(str) {
		if(typeof(str)!="string")return "";
		if (arguments.length <= 1)
			return str;
		var lastIndex = arguments.length - 2;
		for (var i = 0; i <= lastIndex; i++)
			str = str.replace(new RegExp("\\{" + i + "\\}", "gi"), arguments[i + 1]);
		return str;
	};
}
var QS_Calendar=function(callback){
    this.containerId = null;
    this.container = null;
    this.profile={
		fixHeight:true
	};
    this.id = null;
    this.el = null;
    this.dataEl=null;
    this.html=null;
	this.callback={};
	$.extend(this.callback,callback);//for the third party
    this.currentTab=null;
    this.tabMenu=null;
    this.dataScrollPN =null;
	this.staticValue={
		minWidth:800,
		tabMenuHeight:30,
		noDataMessage:"No data available."
	};
	this.headInfo = {//for terminal
	    "0":[{
            header: 'Company',
            dataIndex: 'company',
            dataType: 'string',
            className: "col1 col-company"
        },{
            header: 'Ticker',
            dataIndex: 'ticker',
            dataType: 'string',
            className: "col2 col-ticker"
        },{
            header: 'Time (ET)',
            dataIndex: 'time',
            dataType: 'string',
            className: "col8b col-time"
        },{
            header: 'Wall St EPS Est',
            dataIndex: 'wallStEPSEst',
            dataType: 'string',
            className: "col8b col-wallStEPSEst"
        },{
            header: 'Actual EPS',
            dataIndex: 'actualEPS',
            dataType: 'string',
            className: "col8b col-actualEPS"
        }],
		"1":[{
            header: 'Company',
            dataIndex: 'name',
            dataType: 'string',
            className: "col-22 col-company"
        },{
            header: 'Ticker',
            dataIndex: 'ticker',
            dataType: 'string',
            className: "col-6 col-ticker"
        },{
            header: 'Brokerage Firm',
            dataIndex: 'brokerageName',
            dataType: 'string',
            className: "col-23 col-brokerageName"
        },{
            header: 'Ratings Change',
            dataIndex: 'oldActionType',
			renderer: function(txt, obj){
                return String.format("{0}>>{1}",txt,obj.actionType);
            },
            dataType: 'string',
            className: "col-30 col-ratingsChange"
        },{
            header: 'Pricing Target',
            dataIndex: 'targetPrice',
            dataType: 'string',
			renderer: function(txt, obj){
				if($.trim(txt)!=""){
					return (obj.oldTargetPrice&&$.trim(obj.oldTargetPrice)!="")? String.format("{0}>>{1}",obj.oldTargetPrice,txt):txt;
				}else{
					return "--";
				}
            },
            className: "col-14 col-right col-priceTarget"
        }],
		"2":[{
            header: 'Priced On',
            dataIndex: 'DatePriced',
            dataType: 'date',
            className: "col-9 col-pricedOn"
        },{
            header: 'Company',
            dataIndex: 'Company',
            dataType: 'string',
            className: "col-22 col-company"
        },{
            header: 'Ticker',
            dataIndex: 'Ticker',
            dataType: 'string',
            className: "col-6 col-ticker"
        },{
            header: 'Shares Initial',
            dataIndex: 'InitialShares',
            dataType: 'string',
            className: "col-14 col-right col-si"
        },{
            header: 'Shares Revised',
            dataIndex: 'RevisedShares',
            dataType: 'hide',
            className: "col-14 col-right"
        },{
            header: 'Range Initial',
            dataIndex: 'InitialLowRange',
            dataType: 'string',
            renderer: function(txt, obj){
				if($.trim(txt)!=""){
					return (obj.InitialHighRange&&$.trim(obj.InitialHighRange)!="")? String.format("{0}-{1}",txt,obj.InitialHighRange):txt;
				}else{
					return "--"
				}
            },
            className: "col-14 col-right col-ri"
        },{
            header: 'Range Revised',
            dataIndex: 'RevisedLowRange',
            dataType: 'string',
            renderer: function(txt, obj){
				if($.trim(txt)!=""){
					return (obj.RevisedHighRange&&$.trim(obj.RevisedHighRange)!="")? String.format("{0}-{1}",txt,obj.RevisedHighRange):txt;
				}else{
					return "-"
				}
            },
            className: "col-14 col-right col-rr"
        },{
            header: 'Priced',
            dataIndex: 'ShareValue',
            dataType: 'string',
            renderer: function(txt){
				return (txt&&$.trim(txt)!="")?txt:"--";
            },
            className: "col-6 col-right col-priced"
        },{
            header: 'Open',
            dataIndex: 'OpendedShareValue',
            dataType: 'string',
            renderer: function(txt, obj){
				return (txt&&$.trim(txt)!="")?txt:"--";
            },
            className: "col-6 col-right col-open"
        }],
		"3":[{
            header: 'Company',
            dataIndex: 'name',
            dataType: 'string',
            className: "col-14 col-company"
        },{
            header: 'Ticker',
            dataIndex: 'ticker',
            dataType: 'string',
            className: "col-14 col-ticker"
        },{
            header: 'Ratio',
            dataIndex: 'ratio',
            dataType: 'string',
            className: "col-14 col-ratio"
        },{
            header: 'Payable',
            dataIndex: 'payable',
            dataType: 'date',
            className: "col-14 col-payableDate"
        },{
            header: 'Ex-Date*',
            dataIndex: 'exDate',
            dataType: 'date',
            className: "col-14 col-exDate"
        },{
            header: 'Announced',
            dataIndex: 'announced',
            dataType: 'date',
            className: "col-14 col-announceDate"
        },{
            header: 'Optionable',
            dataIndex: 'optionable',
            dataType: 'string',
			renderer: function(txt){
                return txt?"Yes":"";
            },
            className: "col-14 col-optionable"
        }],
        "4": [{
            header: 'Date',
            dataIndex: 'date',
            dataType: 'date',
            dataFormat: 'engMonth',
            className: "col-9 col-engMonth"
        }, {
            header: 'ET',
            dataIndex: 'time',
            dataType: 'string',
            renderer: function(txt){
                return txt.substring(0, 5)
            },
            className: "col-6 col-time"
        }, {
            header: 'Release',
            dataIndex: 'release',
            dataType: 'string',
            renderer: function(txt, obj){
                return (obj.resourceId == '' ? txt : '<a class="econ_cal_link" href="javascript:void(0)" resourceId="' + obj.resourceId + '">' + txt + '</a>');
            },
            className: "col-25 col-resourceId"
        }, {
            header: 'For',
            dataIndex: 'period',
            dataType: 'string',
            className: "col-6 col-period"
        }, {
            header: 'Actual',
            dataIndex: 'afterReleaseActual',
            dataType: 'string',
            renderer: function(txt){
                return txt == '' ? '--' : txt;
            },
            className: "col-6 col-right col-afterReleaseActual"
        }, {
            header: 'Briefing.com',
            dataIndex: 'briefingComEstimate',
            dataType: 'string',
            renderer: function(txt){
                return txt == '' ? '--' : txt;
            },
            className: "col-12 col-right col-briefingComEstimate"
        }, {
            header: 'Consensus',
            dataIndex: 'consensusEstimate',
            dataType: 'string',
            renderer: function(txt){
                return txt == '' ? '--' : txt;
            },
            className: "col-12 col-right col-consensusEstimate"
        }, {
            header: 'Prior',
            dataIndex: 'priorReleaseActual',
            dataType: 'string',
            renderer: function(txt){
                return txt == '' ? '--' : txt;
            },
            className: "col-9 col-right col-priorReleaseActual"
        }, {
            header: 'Revised from',
            dataIndex: 'OriginallyReportedActual',
            dataType: 'string',
            renderer: function(txt){
                return txt == '' ? '--' : txt;
            },
            className: "col-12 col-right col-OriginallyReportedActual"
        }],
		"5":[{
            header: 'Start Date',
            dataIndex: 'dateTime',
            dataType: 'date',
            dataFormat: 'date',
            className: "col-12 col-startDate"
        },{
            header: 'End Date',
            dataIndex: 'endDate',
            dataType: 'date',
            dataFormat: 'date',
            className: "col-12 col-endDate"
        },{
            header: 'Time',
            dataIndex: 'dateTime',
            dataType: 'date',
            dataFormat: 'time',
            className: "col-12 col-time"
        },{
            header: 'Event',
            dataIndex: 'event',
            dataType: 'string',
			renderer: function(txt,obj){
				var url=obj.url;
				return url!=''?'<a class="econ_cal_link" href="'+url+'" target="blank">'+txt+'</a>':txt;
            },
            className: "col-60 col-event"
        }]
    };
	this.firstTag=true;
    this.serviceCode=typeof QSPC!='undefined'?(QSPC.checkPermission(2.16)?'TRADERCAL':QSPC.checkPermission(2.15)?'INPLAYCAL':'CORECAL'):serviceCode||"CORECAL";
};
QS_Calendar.prototype=$.extend(false,{
		tabMenuData:[{//for terminal
				txt: "Earnings",
				id: 0,
				closable: false
			},{
				txt: "Up/Downgrades",
				id: 1,
				closable: false
			},
			{
				txt: "IPO",
				id: 2,
				closable: false
			},
			{
				txt: "Splits",
				id: 3,
				closable: false
			},
			{
				txt: "Economic",
				id: 4,
				closable: false
			},
			{
				txt: "Events",
				id: 5,
				closable: false
			}
		],
		newsVendor:"Briefing",
		lastActiveTabId:0
	},typeof QSAPI_calendar!='undefined'?QSAPI_calendar:{},{
    init:function(containerId,profile,sId){
        this.containerId=containerId;
        this.container = $('#'+containerId);         
        this.id=sId;
        $.extend(true,this.profile,profile);
        this.html='<div class="rtq-calendar">'+(typeof QSAPI_calendar!='undefined'?'<div class="qs-calendars-loading"><img src="common/loading.gif" /></div>':'')+'<div class="hd"><div class="tabmenu"></div></div><div class="bd"><div class="data"></div></div></div>'
        this.el=$(this.html);
		if (typeof QSAPI_calendar != 'undefined') {
			this.loadingEl = this.el.find(".qs-calendars-loading");
		}
        this.el.appendTo(this.container);
        if(profile){
            this.lastActiveTabId=profile.lastActiveTabId||0;
        }
        this.dataEl=this.el.find('div.data');
        this.dataScrollPN = new Util.ScrollPanel($('div.data',this.el), {delayRun:false}, {
            onScroll: function(sl, st){
            }
        });
        this.createMenu();  
    },
	_createTimeHtml:function(date,isHideFont){
        isHideFont=isHideFont===true?true:false;
        if(isHideFont){
            return '<div class="update">'+date+'</div>';
        }else{
            return '<div class="update">Updated: '+date+'</div>';
        }
        
    },
	setIfreamOnFirst:function(){
        if(typeof this.callback.onLoad=='function'){
            this.callback.onLoad({
                component: "calendars",
                height: this.el.height(),
				minWidth : this.staticValue.minWidth
            });
            this.firstTag = false;
        }
    },
	setIfreamHeight:function(){
        if(typeof this.callback.onHeightChange=='function'){
            var height=this.el.height();
            if(this.lastHeightChange!=height){
                this.callback.onHeightChange({
                     component: "calendars",
                     height:height
                });
                this.lastHeightChange=height;
            }
        }
    },
    createMenu:function(){
        var self=this;
        this.tabMenu=new Util.TabMenu($('.tabmenu',this.el)[0], this.tabMenuData, {
            onActive: function(tab){
                self.currentTab=tab;
                self.createPage(tab.id);
            }
        },{
            width: 100,
            autoResize: false,
            autoFixtoText: true,
            tabsList:true,
            activeTabId:self.lastActiveTabId
        });
    },
    
    createPage:function(type){
        var self=this,
            date=new Date(),
            week=date.getDay(),
            year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate();        
        self.showLoading(true);
        if(week==0){
            date=this._addDate(year,month,day,-2);
        }if(week==6){
            date=this._addDate(year,month,day,-1);
        }
        var rtqDate=self._formatDate(date,"yyyy-mm-dd");
        DBHelper.getCalendar(type, rtqDate,this.serviceCode, function(o){
			var data={};
            if (o != null && $.trim(o) != '') {
				data= $.evalJSON(o);
			}
			if(self.currentTab&&self.currentTab.id!=type){
				return true;
			}
			self.dataEl[0].innerHTML='';
            self.dataEl.unbind('click');
            switch (type) {
                case 0:{
                    if(!data["createDate"]){
                        data["createDate"]=rtqDate;
                    }
                    self._createEarnings(data);
                }break;
                case 1:{
					self._createGrades(data);
                }break;
                case 2:{
					self._createIPO(data);
                }break;
                case 3:{
                    self._createSplits(data);
                }break;
                case 4:{
                    self._createEconomic(data);
                }break;
                case 5:{
                    self._createEvents(data);
                }break;
            }
            self.changeOutSize();
            self.hideLoading();
        });        
    },
    changeOutSize:function(w,h){
		var self=this;
        var parent = this.el.parent().parent();
        w = w || parent.width();
        h = h || parent.height();   
		if (!this.profile.fixHeight) {
			this.dataEl.css({
				width: w + "px"
			});
		}else {
			this.dataEl.css({
				width: w + "px",
				height: h - this.staticValue.tabMenuHeight + "px"
			});
			this.dataScrollPN.reSize(w,h-this.staticValue.tabMenuHeight);
		}
		if (self.firstTag) {
            Util.DelayRun('onload', self.setIfreamOnFirst, 100, self);
        }
        else {
            Util.DelayRun('heightchange', self.setIfreamHeight, 100, self);
        }
    },
	//earnings
	_loadContentByDate:function(rptDate){
        var self=this;
        DBHelper.getCalendar("0",rptDate,this.serviceCode,function(data){
            if(data==null||data==''){return false;}
            data=$.evalJSON(data);  
//            if ($.isEmptyObject(data)) {
//                return;
//            }
            if(!data["createDate"]){
                data["createDate"]=rptDate;
            }
            self.dataEl.find('.qs-calendar-earnings')[0].innerHTML=self._createTimeHtml(self._formatDate2(data["createDate"],"engMonth"),true)+self._createBodyHTML(self.headInfo[0],data["earnings"]);
            self.changeOutSize();
        }); 
    },
	_createWeekHtml:function(){
        var html='<div>',date=new Date(),lastWeek,nextWeek;
        var year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate();
        for(var i=1;i<=6;i++){
            date=this._addDate(year,month,day,(i-5)*7);
            if(i==1){
                lastWeek='';
                nextWeek="Week2";
            }else if(i==6){
                lastWeek="Week5";
                nextWeek='';
            }else{
                lastWeek="Week"+(i-1);
                nextWeek="Week"+(i+1);
            }
            if (i == 5) {
                html += '<div id="Week' + i + '" class="week_row week_over">' + this._createWeekDayHtml(date, lastWeek, nextWeek) + '</div>'
            }else{
                html += '<div id="Week' + i + '" class="week_row">' + this._createWeekDayHtml(date, lastWeek, nextWeek) + '</div>'
            }
        }
        html+='</div>';
        return html;
    },
    _createEarnings:function(data){
        var self=this;
        $(this._createWeekHtml()+'<div class="qs-calendar-earnings">'+self._createTimeHtml(self._formatDate2(data["createDate"],"engMonth"),true)+self._createBodyHTML(this.headInfo[0],data["earnings"])+'</div>'+self._createCopyRightHtml("zacks")).appendTo(self.dataEl);     
        var dayEl=self.dataEl.find('.week_row');
        dayEl.bind('click.Earning',function(e){
            var target=$(e.target);
            var parent=target.closest('div');
            if(e.target.tagName.toLowerCase()=='a'&& parent.hasClass('week_switch')){
                var week=target.attr("week");
                var currWeekEl=self.dataEl.find('div[id="'+week+'"]');
                parent.parent().hide();
                currWeekEl.show();
                var rptDate=currWeekEl.find('.day a').eq(0).attr("rptDate");
                if(dayEl.find('div').hasClass('days_today')){
                    dayEl.find('div').removeClass('days_today').addClass('col-50');
                }
                currWeekEl.find('.day').eq(0).removeClass('col-50').addClass('days_today')
                self._loadContentByDate(rptDate);
            }
            if(e.target.tagName.toLowerCase()=='a'&&parent.hasClass('day')){
                var rptDate=target.attr("rptDate"); 
                if(dayEl.find('div').hasClass('days_today')){
                    dayEl.find('div').removeClass('days_today').addClass('col-50');
                }
                target.parent().removeClass('col-50').addClass('days_today');
                self._loadContentByDate(rptDate);
            }
        });
    },
    _createWeekDayHtml:function(date,lastWeek,nextWeek){
        var year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate(),
            week=date.getDay(),
            currentDate=this._formatDate(new Date(),'yyyy-mm-dd');
        if(week==0){
            date=this._addDate(year,month,day,-2);
        }
        if(week==6){
            date=this._addDate(year,month,day,-1);
        }
        var html='<div class="week_switch">',
            lastDate,lastDateShow,
            year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate(),    
            week=date.getDay();
        
        if(lastWeek==''){
            html+='<a week="'+nextWeek+'" class="qs-calendar-nextWeek">Next Week</a></div>';
        }else if(nextWeek==''){
            html+='<a week="'+lastWeek+'" class="qs-calendar-lastWeek">Last Week</a></a></div>';
        }else{
            html+='<a week="'+lastWeek+'" class="qs-calendar-lastWeek">Last Week</a><span class="qs-calendar-pipe">|</span><a week="'+nextWeek+'" class="qs-calendar-nextWeek">Next Week</a></div>';
        }
        for(var i=0;i<5;i++){
            lastDate=this._formatDate(this._addDate(year,month,day,i-week+1),'yyyy-mm-dd');
            lastDateShow=this._formatDate(this._addDate(year,month,day,i-week+1),'monthEng');
            if (i == 0) {
                html += '<div class="'+(lastDate==currentDate?'days_today':'col-50')+' day">&nbsp;&nbsp;<a rptDate="' + lastDate + '">' + lastDateShow + '</a></div>';
            }else {
                html += '<div class="'+(lastDate==currentDate?'days_today':'col-50')+' day">|&nbsp;<a rptDate="' + lastDate + '">' + lastDateShow + '</a></div>'
            }
        }
        return html;
    },
    _addDate:function(y,m,d,n){//n can be positive or negative
        var d = new Date(y,m-1,d);
        d.setDate(d.getDate()+n);
        return d;
    },
    _formatDate:function(date,type){
        var year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate(),
            dateStr,
            monthCodes={"01":"Jan","02":"Feb","03":"Mar","04":"Apr","05":"May","06":"Jun",
            "07":"Jul","08":"Aug","09":"Sep","10":"Oct","11":"Nov","12":"Dec"};
        if(type=="yyyy-mm-dd"){
            dateStr=year+"-"+month+"-"+day;
        }
        if(type=="monthEng"){
            dateStr=monthCodes[month]+" "+day;
        }
        return dateStr;
    },
    _formatDate2:function(str,format){
        if(str&&str!=null&&str.length!=0){
            var month=str.substring(5,7),
			year=str.substring(0,4),
            day=str.substring(8,10),
			time=str.substring(11,16);
            monthCodes={"01":"Jan","02":"Feb","03":"Mar","04":"Apr","05":"May","06":"Jun",
            "07":"Jul","08":"Aug","09":"Sep","10":"Oct","11":"Nov","12":"Dec"};
            if(format=='engMonth'){
                return monthCodes[month]+" "+day;
            }if(format=="mm-dd-yyyy"){
                return month+"-"+day+"-"+str.substring(0,4);
            }if(format=="date"){
				return day+"-"+monthCodes[month]+"-"+year;
			}if(format=="time"){
				return time+" ET";
			}
            return day+" "+monthCodes[month];
        }
        return '--';
    },
   
    _createGrades:function(data){
        $(this._createTimeHtml(this._formatDate2(data["createDate"],"mm-dd-yyyy"))+'<div class="qs-calendar-grades"><p><strong>Upgrades</strong></p>'+this._createBodyHTML(this.headInfo[1],data["upgraded"])+'<p><strong>Downgrades</strong></p>'+this._createBodyHTML(this.headInfo[1],data["downgraded"])+'</div>'+this._createCopyRightHtml("briefing")).appendTo(this.dataEl);   
    },
    _createIPO:function(data,title){
        $(this._createTimeHtml(this._formatDate2(data["createDate"],"mm-dd-yyyy"))+'<div class="qs-calendar-ipo"><p><strong>Week of : Priced</strong></p>'+this._createBodyHTML(this.headInfo[2],data["Priced"])+'<p><strong>Week of : Expected</strong></p>'+this._createBodyHTML(this.headInfo[2],data["Expected"])+this._createCopyRightHtml("briefing")).appendTo(this.dataEl);   
    },
    _createSplits:function(data){
        $(this._createTimeHtml(this._formatDate2(data["createDate"],"mm-dd-yyyy"))+'<div class="qs-calendar-splits">'+this._createBodyHTML(this.headInfo[3],data["splits"],'<div class="text1">Blue text indicates announcement within the past week.</div>')+'<div class="reproduction">* Ex-Date is the date that the stock price is scheduled to adjust on the respective exchange.</div>'+this._createCopyRightHtml("briefing")).appendTo(this.dataEl);
    },
   _createEconomic:function(data){
        $(this._createTimeHtml(this._formatDate2(data["createDate"],"mm-dd-yyyy"))+'<div class="qs-calendar-economic">'+this._createBodyHTML(this.headInfo[4],data["economic"])+'<div class="reproduction"><strong>Calendar key:</strong><br>Actual refers to the actual figures after their release.<br>Briefing.com refers to Briefing.com\'s forecast.<br>'+
              'Consensus represents the market consensus estimate for each indicator.<br>'+
              'Prior represents the last actual for each indicator. In cases where the release is a revision to an earlier estimate, as is possible with GDP, productivity, and U of Michigan sentiment, the last actual refers to the preliminary estimate for the same period. After a report is released, the Prior column reflects the prior figure as revised.<br>'+
              'The Revised From column lists the prior number as it was originally reported, ie before revision.<br>'+
              'Not included: Mitsubishi and Redbook chain store indexes are released every Tuesday morning. M2 is released every Thursday at 16:30 ET.</div>'+this._createCopyRightHtml("briefing")).appendTo(this.dataEl);
        var self=this;
        this.dataEl.bind('click.Economic',function(e){
            var target=$(e.target);
			if(!target.hasClass('econ_cal_link')) return;
            var resourceId=target.attr('resourceId'),til=target.text();
            var postData={};
            postData["pTeam"]='NT';
            postData["tpl"]='Generic';
            postData["rId"]=resourceId;
            if (typeof QSAPI_calendar != 'undefined') {
                var url=DBHelper.URLs.getNewsContentURL+"?pTeam="+postData["pTeam"]+"&tpl="+postData["tpl"]+"&rId="+encodeURIComponent(postData["rId"])+"&format=html&vendor="+self.newsVendor;
                window.open(url,"displayWindow","toolbar=no,directories=no,status=no,scrollbars=yes,resizable=yes,menubar=no,width=700,height=800");
            }else{ 
                GB_NewsDataManager.getNewsContent(postData, function(o){
                    if (o == null || o == '') {
                        return;
                    }
                    var list = eval("(" + o + ")");
                    var tl = (til == null ? "" : til), ct = (list.content == null ? "" : list.content), str = '<div><div class="content-bd">' + ct + '</div><div class="rtn-content-ft"><img src="IM/logo_briefing.png" height="38px"/><span>Copyright @ 2012 Briefing.com, Inc. All rights reserved.</span></div></div>';
                    if (typeof workspaceManager != 'undefined') {
                        workspaceManager.openNewsDetailWin(tl, str);
                    }
                });
            }
        });
    },
	_createEvents:function(data){
		 $(this._createTimeHtml(this._formatDate2(data["createDate"],"mm-dd-yyyy"))+'<div class="qs-calendar-events">'+this._createBodyHTML(this.headInfo[5],data["events"])+this._createCopyRightHtml("briefing")).appendTo(this.dataEl);
    },
	_createBodyHTML:function(headinfo,data,evendom,odddom){
		var bodyData=data||[];//no data available
		var html='<div class="rtq_table_wrap"><div class="header_row">',hide="";
		for (var i = 0, l = headinfo.length; i < l; i++) {
			hide="";
			if(headinfo[i].dataType == 'hide'){
				hide=' style="display:none;"';
			}
			html += '<div class="' + headinfo[i].className + '"'+ hide +'>' + headinfo[i].header + '</div>';
		};
		html += '</div>';
		var len=bodyData.length,col=null,value=null;
		
		for (var i = 0; i < len; i++) {
			if ((i + 1) & 1) {//even
				html += '<div class="rtq_dk_Row">';
			}
			else {
				html += '<div class="rtq_lt_Row">';
			}
			for (var j = 0, l = headinfo.length; j < l; j++) {
				col = headinfo[j],hide="";
				value = bodyData[i][col.dataIndex];
				if (col.dataType == 'date') {
					value = this._formatDate2(value, col.dataFormat);
				}else if(col.dataType == 'hide'){
					hide=' style="display:none;"';
				}
				if (typeof col.renderer == 'function') {
					value = col.renderer(value, bodyData[i]);
				}
				html += '<div class="' + col.className +'"'+  hide +'>' + value + '</div>';
			};
			html += '</div>';
			if((i & 1)&&evendom){
				html+=evendom;
			}else if(odddom){
				html+=odddom;
			}
		}
		if(len==0){
			html+="<div>No data available.</div>";
		}
		return html+"</div>";
	},
    _createCopyRightHtml:function(type){
        var html='';
        if (type == "briefing") {
            html='<div class="reproduction copyright"><div class="briefingLogo"></div><div class="rightContent"><span>Copyright &copy; 2012 Briefing.com, Inc.</span><span> All rights reserved.</span></div></div>';
        }
        if(type=='zacks'){
            html='<div class="zacksCopyRight">'+
                 '<div><a target="_blank" href="http://news.morningstar.com/BriefNet/EarningsCal_popup.html">Earnings Release Date Data</a> Provided by <a target="_blank" href="http://www.zacks.com">ZACKS Investment Research, Inc.</a><br/>'+
                 '* The expected earnings release date for this firm has been estimated by ZACKS, based upon the company\'s historical report dates.'+
                 '</div></div>';
        }
        return html;
    },
    saveConfig:function(){
        return {
            lastActiveTabId:this.currentTab.id,
            title: this.getTitle()
        };      
    },
    clear:function(){
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }   
});
